package com.example.web.demos.filter;

import com.alibaba.fastjson.JSON;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author: scout.du
 * @date: 2023/02/01 15:06
 **/
@Slf4j
public class ThreadNameFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        String[] split = UUID.randomUUID().toString().split("-");
        String uuid = split[0]+split[1]+split[2];
        Thread.currentThread().setName(uuid.toUpperCase().substring(1));

        String uri = ((HttpServletRequest)request).getRequestURI();
        String queryString = ((HttpServletRequest)request).getQueryString();
        if (!ObjectUtils.isEmpty(queryString)){
//            uri = uri +"?"+ queryString;
            uri = String.format("%s?%s",uri,queryString);
        }
        String method = ((HttpServletRequest) request).getMethod();
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        Map<String,String> map = new HashMap<>();
        Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
        while (headerNames.hasMoreElements()){
            String header = headerNames.nextElement();
            map.put(header,httpServletRequest.getHeader(header));
        }



        log.info("Uri:{}",uri);
        log.info("Method:{}",method);
        log.info("Headers");
        System.out.println(JSON.toJSONString(map,true));

//        ServletInputStream inputStream = httpServletRequest.getInputStream();
        InputStream requestInputStream = request.getInputStream();
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        int bytesRead;
        byte[] data = new byte[1024];
        while ((bytesRead = requestInputStream.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, bytesRead);
        }
        log.info("Body");
        String body = buffer.toString();
        System.out.println(body);



        if (3>1){
            PrintWriter writer = response.getWriter();
            writer.print("over");
            return;
        }

        response.setContentType("text/html");
        chain.doFilter(request,response);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
